package com.cqemme.activitiservice.listener;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cqemme.activitiservice.config.GetSpringBean;
import com.cqemme.activitiservice.dao.SchoolTaskDao;
import com.cqemme.activitiservice.entity.SchoolTaskEntity;
import com.cqemme.activitiservice.feign.EsFeign;
import com.cqemme.comm.po.PutDocPo;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.delegate.event.ActivitiEntityEvent;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.ActivitiEventListener;
import org.activiti.engine.repository.ProcessDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Date;
import java.util.Map;

@Component
public class ComActivitiEventListener implements ActivitiEventListener, Serializable {



    @Autowired
    private SchoolTaskDao schoolTaskDao;

    @Resource
    private EsFeign esFeign;

    /**
     * activiti全局事件接收器
     */
    @Override
    public void onEvent(ActivitiEvent event) {
//        switch (event.getType()) {
//            //流程开始
//            case PROCESS_STARTED:
//                proStart(event);
//                break;
//            //流程结束
//            case PROCESS_COMPLETED:
//                proOver(event);
//                break;
//            //任务开始
//            case TASK_CREATED:
//                taskCreate(event);
//                break;
//            //任务完成
//            case TASK_COMPLETED:
//                taskOver(event);
//                break;
//            //流程结束
//            case PROCESS_CANCELLED:
//                proOver(event);
//            default:
//        }
    }

    /**
     * 这个是必须要的，监听异常处理策略
     *
     * @return
     */
    @Override
    public boolean isFailOnException() {
        return false;
    }

    /**
     * 流程开始做记录
     *
     * @param event
     */
    public void proStart(ActivitiEvent event) {
        //这个不能直接通过@Autowried注入，会报错找不到，可能本类成为bean的时候RuntimeService还没成为bean
        RuntimeService runtimeService = GetSpringBean.getBean(RuntimeService.class);
        RepositoryService repositoryService = GetSpringBean.getBean(RepositoryService.class);

        String instanceId = event.getProcessInstanceId();
        String schoolId = runtimeService.getVariable(instanceId, "schoolId").toString();
        String defineId = event.getProcessDefinitionId();

        ProcessDefinition process = repositoryService.createProcessDefinitionQuery()
                .processDefinitionId(defineId)
                .singleResult();
        String proName = process.getName();

        //组装流程启动数据
//        SchoolTaskEntity schoolTaskEntity = new SchoolTaskEntity();
//        schoolTaskEntity.setScProId(insertSchoolPro(schoolId, defineId));
//        schoolTaskEntity.setName(proName);
//        schoolTaskEntity.setTaskId(instanceId);
//        schoolTaskEntity.setInstanceId(instanceId);
//        schoolTaskEntity.setType(1);
//        schoolTaskEntity.setStatus(2);
//        schoolTaskEntity.setCreateTime(new Date());
//        schoolTaskDao.insert(schoolTaskEntity);

        //存es引擎
        PutDocPo send = new PutDocPo();
        String docName = (schoolId + defineId).replaceAll(":", "_");
        send.setDocName(docName);
        //send.setJson(JSONObject.toJSONString(schoolTaskEntity));

        esFeign.putdocAdd(send);
    }

    /**
     * 流程结束更新状态
     *
     * @param event
     */
    public void proOver(ActivitiEvent event) {
        RuntimeService runtimeService = GetSpringBean.getBean(RuntimeService.class);

        String instanceId = event.getProcessInstanceId();
        String schoolId = runtimeService.getVariable(instanceId, "schoolId").toString();
        String defineId = event.getProcessDefinitionId();

        //更新流程为完成状态
        SchoolTaskEntity schoolTaskEntity = new SchoolTaskEntity();
        //es凭这两个字段去更新状态
        schoolTaskEntity.setTaskId(instanceId);
        schoolTaskEntity.setInstanceId(instanceId);
        schoolTaskEntity.setStatus(1);
        schoolTaskEntity.setOverTime(new Date());
        schoolTaskDao.update(schoolTaskEntity, new QueryWrapper<SchoolTaskEntity>()
                .eq("instance_id", instanceId)
                .eq("task_id", instanceId)
        );


        //存es引擎
        PutDocPo send = new PutDocPo();
        String docName = (schoolId + defineId).replaceAll(":", "_");
        send.setDocName(docName);
        send.setJson(JSONObject.toJSONString(schoolTaskEntity));

        esFeign.putdocAdd(send);
    }

    /**
     * 任务创建做记录
     *
     * @param event
     */
    public void taskCreate(ActivitiEvent event) {
        RuntimeService runtimeService = GetSpringBean.getBean(RuntimeService.class);

        String instanceId = event.getProcessInstanceId();
        String schoolId = runtimeService.getVariable(instanceId, "schoolId").toString();
        String defineId = event.getProcessDefinitionId();
        ActivitiEntityEvent acEntiEv = (ActivitiEntityEvent) event;
        Map eventMap = JSONObject.parseObject(JSONObject.toJSONString(acEntiEv.getEntity()), Map.class);
        String name = eventMap.get("name").toString();
        String taskId = eventMap.get("id").toString();

        //封装任务数据
//        SchoolTaskEntity schoolTaskEntity = new SchoolTaskEntity();
//        schoolTaskEntity.setScProId(insertSchoolPro(schoolId, defineId));
//        schoolTaskEntity.setName(name);
//        schoolTaskEntity.setTaskId(taskId);
//        schoolTaskEntity.setInstanceId(instanceId);
//        schoolTaskEntity.setType(2);
//        schoolTaskEntity.setStatus(2);
//        schoolTaskEntity.setCreateTime(new Date());
//
//        schoolTaskDao.insert(schoolTaskEntity);

        //存es引擎
        PutDocPo send = new PutDocPo();
        String docName = (schoolId + defineId + name).replaceAll(":", "_");
        send.setDocName(docName);
       // send.setJson(JSONObject.toJSONString(schoolTaskEntity));

        esFeign.putdocAdd(send);

    }

    /**
     * 任务完成做更新状态
     *
     * @param event
     */
    public void taskOver(ActivitiEvent event) {

        RuntimeService runtimeService = GetSpringBean.getBean(RuntimeService.class);

        String instanceId = event.getProcessInstanceId();
        String schoolId = runtimeService.getVariable(instanceId, "schoolId").toString();
        String defineId = event.getProcessDefinitionId();
        ActivitiEntityEvent acEntiEv = (ActivitiEntityEvent) event;
        Map eventMap = JSONObject.parseObject(JSONObject.toJSONString(acEntiEv.getEntity()), Map.class);
        String name = eventMap.get("name").toString();
        String taskId = eventMap.get("id").toString();


        //更新任务状态
        SchoolTaskEntity schoolTaskEntity = new SchoolTaskEntity();
        //es凭这两个字段去更新
        schoolTaskEntity.setTaskId(taskId);
        schoolTaskEntity.setInstanceId(instanceId);
        schoolTaskEntity.setStatus(1);
        schoolTaskEntity.setOverTime(new Date());

        schoolTaskDao.update(schoolTaskEntity, new QueryWrapper<SchoolTaskEntity>()
                .eq("instance_id", instanceId)
                .eq("task_id", taskId)
        );

        //存es引擎
        PutDocPo send = new PutDocPo();
        String docName = (schoolId + defineId + name).replaceAll(":", "_");
        send.setDocName(docName);
        send.setJson(JSONObject.toJSONString(schoolTaskEntity));

        esFeign.putdocAdd(send);

    }



}
